package com.suncnpap.api.controller;

import com.suncnpap.library.model.BookLoss;
import com.suncnpap.library.model.BorrowBook;
import com.suncnpap.library.model.BorrowBookInfo;
import com.suncnpap.library.model.BorrowBookRecord;
import com.suncnpap.library.model.IntegralSet;
import com.suncnpap.library.model.Library;
import com.suncnpap.library.model.ReturnBook;
import com.suncnpap.library.service.BookLossService;
import com.suncnpap.library.service.BorrowBookRecordService;
import com.suncnpap.library.service.BorrowBookService;
import com.suncnpap.library.service.ChineseClassificationService;
import com.suncnpap.library.service.CollectionChangeService;
import com.suncnpap.library.service.IntegralSetService;
import com.suncnpap.library.service.LibraryService;
import com.suncnpap.library.service.ReturnBookService;
import com.suncnpap.reader.model.Reader;
import com.suncnpap.reader.model.ReaderType;
import com.suncnpap.reader.service.ReaderService;
import com.suncnpap.reader.service.ReaderTypeService;
import com.suncnpap.statistics.annotation.LogType;
import com.suncnpap.statistics.annotation.SysLog;
import com.suncnpap.system.model.Admin;
import com.suncnpap.system.model.Config;
import com.suncnpap.system.service.AdminService;
import com.suncnpap.system.service.ConfigService;
import com.suncnpap.system.service.HolidayService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.app.util.beanutil.BeanUtil;
import com.app.util.common.DateUtil;
import com.app.util.common.HandlerResult;
import com.app.util.common.ResponseUtil;
import com.app.util.common.UuidUtil;
import com.app.util.database.mybatis.Page;
import com.app.util.database.mybatis.QueryType;
import com.suncnpap.base.common.GlobaUser;
import com.suncnpap.base.controller.BaseController;

/** 
 * 说明：接口Controller
 */
@Controller
@RequestMapping(value="/api")
public class LibraryApiController extends BaseController {
	
	//private static final Logger log = Logger.getLogger(LibraryController.class);
	
	
	@Autowired
	CollectionChangeService collectionChangeService;
	
	@Autowired
	ChineseClassificationService chineseClassificationService;
	
	@Autowired
	LibraryService libraryService;
	
	@Autowired
	ReaderService readerService;
	
	@Autowired
	BorrowBookService borrowBookService;
	
	@Autowired
	BorrowBookRecordService borrowBookRecordService;
	
	@Autowired
	ReturnBookService returnBookService;
	
	@Autowired
	ReaderTypeService readerTypeService;
	
	@Autowired
	BookLossService bookLossService;
	
	@Autowired
	IntegralSetService integralSetService;
	
	@Autowired
	HolidayService holidayService;
	
	@Autowired
	ConfigService configService;
	
	@Autowired
	AdminService adminService;
	
	/**
	 * 借阅处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/borrowBook")//,method=RequestMethod.POST
	@SysLog(type=LogType.BOOKBORROW)
	public void borrowBook(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strSchoolId = this.getParameter("strSchoolId");
			String strUserId = this.getParameter("strUserId");
			String strBookBarcode = this.getParameter("strBookBarcode");
			String strReaderCardNumber = this.getParameter("strReaderCardNumber");
			
			Library library = libraryService.findByBookBarcode(strBookBarcode, strSchoolId);
			BookLoss bookLoss = bookLossService.findByBookBarcode(strBookBarcode, strSchoolId);
			if(library!=null){
				if(bookLoss==null){
					BorrowBook borrowBook = borrowBookService.findByBookBarcode(strBookBarcode, strSchoolId);
					
					if(borrowBook==null){
						Reader reader = readerService.findByCardNumber(strReaderCardNumber, strSchoolId);
						if(reader != null){
							Page page = new Page();
							page.addQueryAnd("strSchoolId", strSchoolId);
							page.addQueryAnd("strStartTime", QueryType.markGTEQ, DateUtil.get(new Date(), "yyyy-mm-dd"));
							page.addQueryAnd("strEndTime", QueryType.markLTEQ, DateUtil.get(new Date(), "yyyy-mm-dd"));
							int count = holidayService.findCount(page);
							
							if(count>0){
								result.setCode(1);
								result.setMessage("假期内不能借书");
							}else{
//								ReaderType readerType = readerTypeService.findById(reader.getStrReaderTypeId());
								Config config = configService.findBySchoolId(strSchoolId);
								
								Calendar cal = Calendar.getInstance();
								
								Admin admin = adminService.findByUserId(strUserId, strSchoolId);
								BorrowBook obj = new BorrowBook();
								obj.setStrId(UuidUtil.get32UUID());//主键ID
								obj.setDtCreatDate(new Date());//创建时间
								obj.setStrCreatId(admin.getStrId());//创建人ID
								obj.setStrCreatName(admin.getStrName());//创建人姓名
								obj.setStrSchoolId(strSchoolId);//独立机构ID
								
								SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
								obj.setDtBorrowDate(sdf.parse(sdf.format(cal.getTime())));
								int intBorrowingDays = 5;
								if(config.getIntDefaultBorrowDays()!=null){
									intBorrowingDays = config.getIntDefaultBorrowDays();
								}
								cal.add(Calendar.DATE, intBorrowingDays);
								obj.setDtReturnDate(cal.getTime());
								obj.setStrBookBarcode(strBookBarcode);
								obj.setStrReaderCardNumber(strReaderCardNumber);
								borrowBookService.add(obj);
								
								BorrowBookRecord borrowBookRecord = new BorrowBookRecord();
								BeanUtil.copyBean(obj, borrowBookRecord);
								borrowBookRecord.setIsReturn(0);
								borrowBookRecord.setIntRenewCount(0);
								borrowBookRecordService.add(borrowBookRecord);
								
								libraryService.updateBorrowById(strBookBarcode, strSchoolId);
								
								IntegralSet integralSet = integralSetService.findBySchoolId(reader.getStrSchoolId());
								if(integralSet!=null){
									reader.setIntIntegral(reader.getIntIntegral()+integralSet.getIntIntegral());
									readerService.update(reader);
								}
							}
						}else{
							result.setCode(1);
							result.setMessage("不存在的读者卡号");
						}
					}else{
						result.setCode(1);
						result.setMessage("该图书已经被借出");
					}
				}else{
					result.setCode(1);
					result.setMessage("该图书已经丢失/损毁");
				}
			}else{
				result.setCode(1);
				result.setMessage("不存在的图书条码");
			}
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 归还处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/returnBook")//,method=RequestMethod.POST
	@SysLog(type=LogType.RETURNBOOK)
	public void returnBook(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strSchoolId = this.getParameter("strSchoolId");
			String strUserId = this.getParameter("strUserId");
			String strBookBarcode = this.getParameter("strBookBarcode");
			String strReaderCardNumber = this.getParameter("strReaderCardNumber");
			
			BorrowBookRecord borrowBookRecord = borrowBookRecordService.findByBookBarcode(strBookBarcode, strSchoolId);
			
			if(borrowBookRecord!=null){
				
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
				borrowBookRecord.setDtReturnDate(sdf.parse(sdf.format(new Date())));
				borrowBookRecord.setIsReturn(1);
				borrowBookRecordService.update(borrowBookRecord);
				
				ReturnBook returnTemp = new ReturnBook();
				BeanUtil.copyBean(borrowBookRecord, returnTemp);
				init(returnTemp);
				returnBookService.add(returnTemp);
				
				Page page = new Page();
				page.addQueryAnd("br.strReaderCardNumber", borrowBookRecord.getStrReaderCardNumber());
				page.addQueryAnd("br.strBookBarcode", borrowBookRecord.getStrBookBarcode());
				page.setUsePage(false);
				page.put("over", "true");
//					page.addQueryAnd("r.strSchoolId", strSchoolId);
				page.addQueryAnd("l.strSchoolId", strSchoolId);
				
				List<BorrowBookInfo> borrowBookRecordList = borrowBookService.listInfo(page).getDataList();
				
				borrowBookService.deleteByBookBarcode(strBookBarcode, strSchoolId);
				
				libraryService.updateReturnById(strBookBarcode, strSchoolId);
				
				Reader reader = readerService.findByCardNumber(borrowBookRecord.getStrReaderCardNumber(), strSchoolId);
				int num = (int) ((borrowBookRecord.getDtReturnDate().getTime()-borrowBookRecord.getDtBorrowDate().getTime())/(24*60*60*1000));
				IntegralSet integralSet = integralSetService.findBySchoolId(strSchoolId);
				if(integralSet!=null){
					int minday = integralSet.getIntMinDay();
					int maxday = integralSet.getIntMaxDay();
					if(minday<=num && maxday>=num ){
						reader.setIntIntegral(reader.getIntIntegral()+integralSet.getIntIntegral());
						readerService.update(reader);
					}
				}
				
//				
//				result.put("borrowBookRecord", borrowBookRecordList);
//				result.put("reader", reader);
//				
//				Config config = configService.findBySchoolId(strSchoolId);
//				result.put("fBookOverdueFineAmount", config.getfBookOverdueFineAmount());
				
				
			}else{
				result.setCode(1);
				result.setMessage("不存在的图书条码或该图书未被借出");
			}
			
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	/**
	 * 借阅处理
	 * @param obj
	 * @param response
	 */
	@RequestMapping(value="/continueBorrowBook")//,method=RequestMethod.POST
	public void continueBorrowBook(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strSchoolId = this.getParameter("strSchoolId");
			String strUserId = this.getParameter("strUserId");
			String strBookBarcode = this.getParameter("strBookBarcode");
			String strReaderCardNumber = this.getParameter("strReaderCardNumber");
			
			BorrowBook obj = borrowBookService.findByBookBarcode(strBookBarcode, strSchoolId);
			if(obj != null){
				Config config = configService.findBySchoolId(strSchoolId);
				BorrowBookRecord borrowBookRecord = borrowBookRecordService.findByBookBarcode(obj.getStrBookBarcode(), strSchoolId);
				
				//系统设置的最大续借次数
				int intMaxRenewCount = config.getIntMaxRenewCount();
				//当前借阅续借次数
				int intRenewCount = borrowBookRecord.getIntRenewCount();
				
				if(intMaxRenewCount>intRenewCount){
					Calendar cal = Calendar.getInstance();
					int intBorrowingDays = 5;
					if(config.getIntDefaultBorrowDays()!=null){
						intBorrowingDays = config.getIntDefaultBorrowDays();
					}
					cal.add(Calendar.DATE, intBorrowingDays);
					obj.setDtReturnDate(cal.getTime());
					borrowBookService.update(obj);
					
					borrowBookRecord.setDtReturnDate(obj.getDtReturnDate());
					borrowBookRecord.setIntRenewCount(borrowBookRecord.getIntRenewCount()+1);
					borrowBookRecordService.update(borrowBookRecord);
				}else{
					result.setCode(1);
					result.setMessage("已超过最大续借次数");
				}
				
			}else{
				result.setCode(1);
				result.setMessage("不存在的图书条码或该图书没有被借出");
			}
			
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/getLibrary")
	public void getLibrary(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strSchoolId = this.getParameter("strSchoolId");
			String strBookBarcode = this.getParameter("strBookBarcode");
			
			Library obj = libraryService.findByBookBarcode(strBookBarcode, strSchoolId);
			if(obj!=null){
				result.put("obj", obj);
			}else{
				result.setCode(1);
				result.setMessage("不存在的图书条码");
			}
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/getReaderInfo")
	public void getReaderInfo(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strCardNumber = this.getParameter("strCardNumber", "");
			String strSchoolId = this.getParameter("strSchoolId", "");
			Reader obj = readerService.findByCardNumber(strCardNumber, strSchoolId);
			if(obj!=null){
				
				//借阅数量 
				Page page = new Page();
				page.addQueryAnd("strReaderCardNumber", strCardNumber);
				page.addQueryAnd("strSchoolId", strSchoolId);
				page.addQueryAnd("isReturn", 0);
				int bookBorrowCount = borrowBookRecordService.findCount(page);
				obj.setStrBookBorrowCount(bookBorrowCount+"");
				
				//超期数量 
				page = new Page();
				page.addQueryAnd("strReaderCardNumber", strCardNumber);
				page.addQueryAnd("strSchoolId", strSchoolId);
				page.addQueryAnd("isReturn", 0);
				page.addQueryAnd("dtReturnDate", QueryType.markLTEQ, new Date());
				int bookOverdueCount = borrowBookRecordService.findCount(page);
				obj.setStrBookOverdueCount(bookOverdueCount+"");
				
				//当前用户在班里排第几名（依据积分排名） 
				page = new Page();
				page.put("user", "1");
				page.put("searchValue",strCardNumber);
				page.addQueryAnd("strSchoolId", strSchoolId);
				page.addQueryAnd("strClassId", obj.getStrClassId());
				int strRanking = readerService.getObjectRanking(page);
				obj.setStrRanking(strRanking+"");
				
				//可借数量 
				ReaderType readerType = readerTypeService.findById(obj.getStrReaderTypeId());
				if(readerType!=null){
					int bookCouldBorrowCount = readerType.getIntNumOfBook()-bookBorrowCount;
					obj.setStrBookCouldBorrowCount(bookCouldBorrowCount+"");
				}else{
					obj.setStrBookCouldBorrowCount(0+"");
				}
				
				result.put("obj", obj);
			}else{
				result.setCode(1);
				result.setMessage("不存在的读者卡号");
			}
			
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/getReaderBorrowInfo")
	public void getReaderBorrowInfo(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strCardNumber = this.getParameter("strCardNumber", "");
			String strSchoolId = this.getParameter("strSchoolId", "");
			
			Reader obj = readerService.findByCardNumber(strCardNumber, strSchoolId);
			if(obj!=null){
				Page page = new Page();
				page.put("over", "true");
				page.addQueryAnd("br.strReaderCardNumber", strCardNumber);
				page.setUsePage(false);
//					page.addQueryAnd("r.strSchoolId", strSchoolId);
				page.addQueryAnd("l.strSchoolId", strSchoolId);
				
				List<BorrowBookInfo> borrowBookList = borrowBookService.listInfo(page).getDataList();
				
				result.put("borrowBookList", borrowBookList);
			}else{
				result.setCode(1);
				result.setMessage("不存在的读者卡号");
			}
			
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/getIntegralTop")
	public void getIntegralTop(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strSchoolId = this.getParameter("strSchoolId", "");
			
			Page page = new Page();
//			page.setUsePage(false);
			page.put("user", "1");
			page.addQueryAnd("strSchoolId", strSchoolId);
			List<Reader> list = readerService.integralList(page).getDataList();
			result.put("list", list);
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/getReaderIntegralRanking")
	public void getReaderIntegralRanking(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strSchoolId = this.getParameter("strSchoolId", "");
			
			Page page = new Page();
			page.setRows(50);
			page.put("user", "1");
			page.addQueryAnd("strSchoolId", strSchoolId);
			List<Reader> list = readerService.integralList(page).getDataList();
			result.put("list", list);
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	@RequestMapping(value="/getClassIntegralRanking")
	public void getClassIntegralRanking(HttpServletRequest request,HttpServletResponse response) throws Exception{
		
		HandlerResult result = new HandlerResult();
		try{
			String strSchoolId = this.getParameter("strSchoolId", "");
			
			Page page = new Page();
			page.setUsePage(false);
			page.put("class", "1");
			page.addQueryAnd("strSchoolId", strSchoolId);
			List<Reader> list = readerService.integralList(page).getDataList();
			result.put("list", list);
		}catch(Exception e){
			result.setCode(1);
			e.printStackTrace();
			throw e;
		}
		ResponseUtil.writeJson(result, response);
	}
	
	public static void main(String[] args){
		//创建http链接
        String urlpath="http://127.0.0.1:92/plib/api/borrowBook";
        try {
            URL url=new URL(urlpath);
            HttpURLConnection httpConn= null;
                httpConn = (HttpURLConnection)url.openConnection();
            assert httpConn != null;
            httpConn.setRequestMethod("POST");      //设置POST方式连接
            httpConn.setDoOutput(true);
            OutputStream output = null;
            //设置请求属性
//            httpConn.setRequestProperty("Content-Type", "text/html");
//            httpConn.setRequestProperty("Charset", "UTF-8");
            String params = "strReaderCardNumber="+"12345";
            params += "&strBookBarcode="+"10011490";
            params += "&strUserId="+"池淮中学";
            params += "&strSchoolId="+"d8f4a58ff0ab40fe9929422c759d4858";
            
            // 获取返回信息
			output = httpConn.getOutputStream();
			output.write(params.getBytes());
			output.flush();
			output.close();
			
            httpConn.connect();
            //获得相应状态
            int resultCode=httpConn.getResponseCode();
            if(HttpURLConnection.HTTP_OK==resultCode){
                StringBuffer sb=new StringBuffer();
                String readLine;
                BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
                while((readLine=responseReader.readLine())!=null){
                    sb.append(readLine).append("\n");
                }
                responseReader.close();
                System.out.println("结果:"+sb);
            }else{
                System.out.println("状态码:"+resultCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
}
